package com.operator.Activitys.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.facebook.common.executors.CallerThreadExecutor;
import com.facebook.common.references.CloseableReference;
import com.facebook.datasource.DataSource;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.backends.pipeline.PipelineDraweeController;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.common.ResizeOptions;
import com.facebook.imagepipeline.core.ImagePipeline;
import com.facebook.imagepipeline.datasource.BaseBitmapDataSubscriber;
import com.facebook.imagepipeline.image.CloseableImage;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import static android.provider.MediaStore.Images.Media.insertImage;

/**
 * 项目名称：
 * 类描述：Fresco(图片加载常用工具类)
 * 创建人：张飞祥
 * 创建时间：2018/04/18 下午2:17
 * 修改人：张飞祥
 * 修改时间：2018/04/18 下午2:17
 * 修改备注：
 */
public class FrescoUtils {
    /**
     *
     * URi方式加载
     * @param uri
     * @param simpleDraweeView
     */
    public static void loadAvatar(Uri uri, SimpleDraweeView simpleDraweeView) {

        //TODO 清理内存 中 相同 的缓存
        ImagePipeline imagePipeline = Fresco.getImagePipeline();
        imagePipeline.evictFromCache(uri);
        //TODO 开始 加载图片
        ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri)
                .build();
        DraweeController controller = Fresco.newDraweeControllerBuilder()
                .setUri(uri)
                .setImageRequest(request)
                .setOldController(simpleDraweeView.getController())
                .build();
        simpleDraweeView.setController(controller);
    }

    /**
     *
     * BitMap方式加载
     * @param bitmap
     * @param simpleDraweeView
     */
    public static void loadBitmap(Context context,Bitmap bitmap, SimpleDraweeView simpleDraweeView) {

        //将 bitmap 转换 Uri
        Uri uri = Uri.parse(insertImage(context.getContentResolver(), bitmap, null,null));

        //TODO 清理内存 中 相同 的缓存
        ImagePipeline imagePipeline = Fresco.getImagePipeline();
        imagePipeline.evictFromCache(uri);
        //TODO 开始 加载图片
        ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri)
                .build();
        DraweeController controller = Fresco.newDraweeControllerBuilder()
                .setUri(uri)
                .setImageRequest(request)
                .setOldController(simpleDraweeView.getController())
                .build();
        simpleDraweeView.setController(controller);
    }

    /**
     * 网络请求加载
     * @param url
     * @param simpleDraweeView
     */
    public static void loadImage(String url, SimpleDraweeView simpleDraweeView) {
        if (TextUtils.isEmpty(url)) {
            url = "http://";
        }
        Uri uri = Uri.parse(url);
        //TODO 开始 加载图片
        ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri)
                .build();
        DraweeController controller = Fresco.newDraweeControllerBuilder()
                .setUri(uri)
                .setImageRequest(request)
                .setOldController(simpleDraweeView.getController())
                .build();
        simpleDraweeView.setController(controller);
    }

    /**
     *
     * 加载本项目中图片
     * @param resId
     * @param simpleDraweeView
     */
    public static void loadLocalImage(int resId, SimpleDraweeView simpleDraweeView) {

        Uri uri = Uri.parse("res://com.operator.Activitys/" + resId);
        ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri)
                .build();
        DraweeController controller = Fresco.newDraweeControllerBuilder()
                .setUri(uri)
                .setImageRequest(request)
                .setOldController(simpleDraweeView.getController())
                .build();
        simpleDraweeView.setController(controller);
    }

    /**
     * 加载项目中 大图片 宽高不变
     * @param resId
     * @param draweeView
     * @param width
     * @param height
     */
    public static void loadLocalBigMap(int resId, SimpleDraweeView draweeView, int width, int height){

        Uri uri = Uri.parse("res://com.odd.Activitys/" + resId);

        ImageRequest request =
                ImageRequestBuilder.newBuilderWithSource(uri)
                        .setResizeOptions(new ResizeOptions(width,height))
                        //缩放,在解码前修改内存中的图片大小, 配合Downsampling可以处理所有图片,否则只能处理jpg,
                        // 开启Downsampling:在初始化时设置.setDownsampleEnabled(true)
                        .setProgressiveRenderingEnabled(true)//支持图片渐进式加载
                        .setAutoRotateEnabled(true) //如果图片是侧着,可以自动旋转
                        .build();

        PipelineDraweeController controller =
                (PipelineDraweeController) Fresco.newDraweeControllerBuilder()
                        .setImageRequest(request)
                        .setOldController(draweeView.getController())
                        .setAutoPlayAnimations(true) //自动播放gif动画
                        .build();

        draweeView.setController(controller);
    }
    //加载大图保持宽高比缩放
    public static void loadResizeImg(final Context context, Uri uri, final SimpleDraweeView simpleDraweeView) {
        ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri)
                .setProgressiveRenderingEnabled(true)
                .build();
        DataSource<CloseableReference<CloseableImage>> dataSource =
                Fresco.getImagePipeline().fetchDecodedImage(request, context);
        dataSource.subscribe(new BaseBitmapDataSubscriber() {
            @Override
            protected void onNewResultImpl(@Nullable Bitmap bitmap) {
                if (bitmap != null) {
                    float height = (UiUtil.getDisplayWidth(context) / (float) bitmap.getWidth()) * bitmap.getHeight();
                    if (Thread.currentThread().getName().equals("main")) {
                        simpleDraweeView.setLayoutParams(new LinearLayout.LayoutParams(UiUtil.getDisplayWidth(context), (int) height));
                    }
                }
            }

            @Override
            protected void onFailureImpl(DataSource<CloseableReference<CloseableImage>> dataSource) {
            }
        }, CallerThreadExecutor.getInstance());

        DraweeController controller = Fresco.newDraweeControllerBuilder()
                .setUri(uri)
                .setImageRequest(request)
                .setOldController(simpleDraweeView.getController())
                .build();
        simpleDraweeView.setController(controller);
    }


    //重新计算listv高度
    public static void reListViewSize(ListView listView, Adapter adapter) {
        int totalHeight = 0;
        for (int i = 0, len = adapter.getCount(); i < len; i++) { // listAdapter.getCount()返回数据项的数目
            View listItem = adapter.getView(i, null, listView);
            listItem.measure(0, 0); // 计算子项View 的宽高
            totalHeight += listItem.getMeasuredHeight(); // 统计所有子项的总高度
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight
                + (listView.getDividerHeight() * (adapter.getCount() - 1));
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }

    //获取网络图片的宽高
    public static BitmapFactory.Options decodeThumbBitmapFromNet(String path){
        InputStream inputStream = null;
        Bitmap bitmap = null;
        BitmapFactory.Options options = new BitmapFactory.Options();
        //设置为true,表示解析Bitmap对象，该对象不占内存
        options.inJustDecodeBounds = true;
        //设置缩放比例
        try {
            URL imgUrl = new URL(path);
            // 使用HttpURLConnection打开连接
            HttpURLConnection urlConn = (HttpURLConnection) imgUrl.openConnection();
            urlConn.setDoInput(true);
            urlConn.setConnectTimeout(10000);
            urlConn.setReadTimeout(10000);
            urlConn.connect();
            // 将得到的数据转化成InputStream
            inputStream = urlConn.getInputStream();
            bitmap = BitmapFactory.decodeStream(inputStream, null, options);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                if(inputStream !=null){
                    inputStream.close();
                }
                if(bitmap !=null){
                    bitmap.recycle();
                    bitmap = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return options;
    }

}
